import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:lib_uikit/lib_uikit.dart';

class GTRefresher extends StatefulWidget {
  final Widget? child;

  /// 返回值: true: 有更多数据, false: 没有更多数据
  final Future<bool> Function()? onRefresh;

  /// 返回值: true: 有更多数据, false: 没有更多数据
  final Future<bool> Function()? onLoading;

  final bool enablePullDown;
  final bool enablePullUp;

  const GTRefresher({
    Key? key,
    this.child,
    this.onRefresh,
    this.onLoading,
    this.enablePullDown = true,
    this.enablePullUp = false,
  }) : super(key: key);

  @override
  GTRefresherState createState() => GTRefresherState();
}

class GTRefresherState extends State<GTRefresher> {
  final RefreshController refreshController = RefreshController();

  @override
  dispose() {
    refreshController.dispose();
    super.dispose();
  }

  toggleRefreshState(bool hasMoreData) {
    refreshController.refreshCompleted();
    if (hasMoreData) {
      refreshController.loadComplete();
    } else {
      refreshController.loadNoData();
    }
  }

  @override
  Widget build(BuildContext context) {
    return SmartRefresher(
      onRefresh: widget.onRefresh != null
          ? () async {
              bool hasMoreData = await widget.onRefresh!();
              toggleRefreshState(hasMoreData);
            }
          : null,
      onLoading: widget.onLoading != null
          ? () async {
              bool hasMoreData = await widget.onLoading!();
              toggleRefreshState(hasMoreData);
            }
          : null,
      header: const GTRefreshHeader(),
      footer: const GTLoadMoreFooter(),
      controller: refreshController,
      enablePullDown: widget.enablePullDown,
      enablePullUp: widget.enablePullUp,
      child: widget.child,
    );
  }
}
